using AdminWeb.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using XW.Web.Framework;
using XW.Web.Framework.Jwt;
using Microsoft.Extensions.Options;
using XW.Core;
using XW.Data;
using Microsoft.IdentityModel.Tokens;
using XW.Utils;
using Microsoft.VisualStudio.Web.CodeGenerators.Mvc.Templates.BlazorIdentity.Pages.Manage;
using System.Threading.Tasks;

namespace AdminWeb.Controllers
{
    /// <summary>
    ///  入口控制器
    /// </summary>
    /// <seealso cref="XW.Web.Framework.BaseController" />
    public class HomeController : BaseController
    {
        private readonly IOptions<JwtSecurityTokenOptions> _jwtOptions;
        private readonly ILogger<HomeController> _logger;
        private readonly SqlSugarRepository<SysUser> _userRep;

        public HomeController(ILogger<HomeController> logger,IOptions<JwtSecurityTokenOptions> jwtOptions, SqlSugarRepository<SysUser> userRep)
        {
            _logger = logger;
            _jwtOptions = jwtOptions;
            _userRep = userRep;
        }
		[Authorize]
		public IActionResult Index()
		{
			var user = _userRep.GetById(this.UserId);
			ViewData["CurrentUser"] = user;
			return View();
		}
		/// <summary>
		/// 首页
		/// </summary>
		/// <returns></returns>
		[Authorize]
		public IActionResult Main()
		{
			return View();
		}

		/// <summary>
		/// BootTest
		/// </summary>
		/// <returns></returns>
		[Authorize]
		public IActionResult BootTest()
		{
			return View();
		}

        [AllowAnonymous]
        public IActionResult Login()
        {
            return View();
        }

        [AllowAnonymous]
        public IActionResult Logout()
        {
            JwtTokenHelper.SignOut(this.HttpContext);
            return RedirectToAction("Login", "Home");
        }
		#region Ajax
		/// <summary>
		/// 管理员登录
		/// </summary>
		/// <returns></returns>
		[AllowAnonymous]
		public async Task<IActionResult> AdminLogin() {
			var body = CommonHelper.GetBody();
			Console.WriteLine(body);
			var data = JsonHelper.ToObject<dynamic>(body);
            string? userName = data.username;
            string? password = data.password;
            var users = _userRep.AsQueryable().Where(u => u.Account == userName).ToList(); 
            if (users.Count() > 0)
            {
                var user = users[0];
                if (password.IsNotNullAndEmpty() && user.Password == CryptoHelper.MD5(string.Format("{0}{1}", user.Salt, password)))
                {
                    string token = JwtTokenHelper.LoginAndGetToken(HttpContext, _jwtOptions.Value, user.Id.ToString(), user.OrgId.ToString(), user.NickName, user.AccountType.ToString(), "xw");
                    user.LastLoginTime = DateTime.Now;
                    await _userRep.AsUpdateable(user).UpdateColumns(u => u.LastLoginTime == DateTime.Now).ExecuteCommandAsync();

                    return GetSuccessResult(new { token = token });
                }
            }
            else
            {
                return GetErrorResult("账号不存在！");
            }
            return GetErrorResult("账号或密码错误！");
        }
        [AllowAnonymous]
		public async Task<IActionResult> AjaxLogin()
		{
            string? codeId = Request.Form["codeId"];
            string? captcha = Request.Form["captcha"];
			if (!CaptchaHelper.Valid(codeId, captcha))
			{
                return GetErrorResult("验证码不正确或不存在！");
            }
            string? userName = Request.Form["username"];
			string? password = Request.Form["password"];
			var users = _userRep.AsQueryable().Where(u => u.Account == userName).ToList();
			//if (users.IsNullOrEmpty())
			//{
			//    return GetErrorResult("用户不存在！");
			//}
			if (users.Count() > 0)
			{
				var user = users[0];
				if (password.IsNotNullAndEmpty() && user.Password == CryptoHelper.MD5(string.Format("{0}{1}", user.Salt, password)))
				{
					string token = JwtTokenHelper.LoginAndGetToken(HttpContext, _jwtOptions.Value, user.Id.ToString(), user.OrgId.ToString(), user.NickName, user.AccountType.ToString(), "xw");
					user.LastLoginTime = DateTime.Now; 
                    await _userRep.AsUpdateable(user).UpdateColumns(u => u.LastLoginTime == DateTime.Now).ExecuteCommandAsync();

                    return GetSuccessResult(new { token = token });
				}
			}
			else
			{
                return GetErrorResult("账号不存在！");
            }
			//if (Request.Form != null && Request.Form["username"] == "admin" && Request.Form["password"] == "123456")
			//{
			//    string token = JwtTokenHelper.LoginAndGetToken(HttpContext, _jwtOptions.Value,"123","123","系统管理员","1","xw");
			//    return GetSuccessResult(new   { token =token });
			//}

			return GetErrorResult("账号或密码错误！");
		}

		/// <summary>
		/// 首页
		/// </summary>
		/// <returns></returns>
		[Authorize]
		public IActionResult AjaxUserInfo()
		{
			var user = _userRep.GetById(this.UserId);
			if (user == null)
			{
				return GetErrorResult("请重新登陆！");
			}
			return GetSuccessResult(user);
		}

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public IActionResult AjaxCaptcha()
        {
            string code = Guid.NewGuid().ToString();
            var img = CaptchaHelper.Gen(code); 
            return GetSuccessResult(new { id = code, img = img });
        }
        /// <summary>
        /// 修改当前用户的备注
        /// </summary>
        /// <returns></returns>
        [Authorize]
		public IActionResult AjaxProfileUpdate() {
			var user = _userRep.GetById(this.UserId);
			if (user == null)
			{
				return GetErrorResult("请重新登陆！");
			}
			string? nickName = this.Request.Form["NickName"];
            string? Introduc = this.Request.Form["Introduc"];
            string? Phone = this.Request.Form["Phone"];
            string? email = this.Request.Form["Email"];
            string? id = this.Request.Form["id"];
			if (id != user.Id.ToString())
			{
				return GetErrorResult("请先刷新后再修改！");
			}
			_userRep.AsUpdateable()
				.SetColumns(u => u.NickName == nickName)
                .SetColumns(u => u.Introduc == Introduc)
                .SetColumns(u => u.Phone == Phone)
                .SetColumns(u => u.Email == email)
                .setColumnsUpdateUserAndTime()
				.Where(u => u.Id == this.UserId).ExecuteCommand();
			return GetSuccessResult(user);

		}
		#endregion


		//public IActionResult Privacy()
  //      {
  //          return View();
  //      }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }


        /// <summary>
        /// 修改当前用户的备注
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public IActionResult ClearCache()
        {
			// 清除缓存
			CacheHelper.Clear();
            return GetSuccessResult("服务端清理缓存成功"); 
        }

    }
}
